<template>
	<div class="user-manage">
		<div class="query-form">
			<el-form ref="form" :inline="true" :model="user">
				<el-form-item label="公式名称" prop="name">
					<el-input v-model="user.name" placeholder="请输入公式名称" />
				</el-form-item>
<!--				<el-form-item label="公式" prop="expression">-->
<!--					<el-input v-model="user.expression" placeholder="请输入公式" />-->
<!--				</el-form-item>-->
				<el-form-item>
					<el-button type="primary" @click="handleQuery">查询</el-button>
					<el-button @click="handleReset('form')">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="base-table">
			<div class="action">
				<el-button type="primary" @click="handleCreate">新增</el-button>
<!--				<el-button type="danger" @click="handlePatchDel" v-has="'user-patch-delete'">批量删除</el-button>-->
			</div>
			<el-table :data="userList" @selection-change="handleSelectionChange">
				<!-- <el-table-column type="selection" width="55" /> -->
				<el-table-column v-for="item in columns" :key="item.prop" :prop="item.prop" :label="item.label"
					:width="item.width" :formatter="item.formatter">
				</el-table-column>
				<el-table-column label="操作" width="250">
					<template #default="scope">
						<el-button @click="handleEdit(scope.row)" size="mini">编辑</el-button>
						 <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row)"
              >删除</el-button
            >
					</template>
				</el-table-column>
			</el-table>
			<el-pagination class="pagination" background layout="prev, pager, next" :total="pager.total"
				:page-size="pager.pageSize" @current-change="handleCurrentChange" />
		</div>
		<el-dialog title="新增" v-model="showModal">
			<el-form ref="dialogForm" :model="userForm" label-width="100px" :rules="rules">
				<el-form-item label="公式名称" prop="name">
					<el-input v-model="userForm.name" placeholder="请输入公式名称" />
				</el-form-item>
        <el-form-item label="公式类型" prop="type">
          <el-select v-model="userForm.type" @change="selectChangedType">
            <el-option :value="1" label="应发工资"></el-option>
            <el-option :value="2" label="实发工资"></el-option>
          </el-select>
        </el-form-item>
				<el-form-item label="公式" prop="expression">
					<el-input v-model="userForm.expression" disabled="true" placeholder="请输入公式" />
					<!-- :disabled="action == 'edit'" -->
				</el-form-item>
				<el-form-item label="公式" prop="expressionList">
					<el-input v-model="userForm.expressionList" disabled="true" placeholder="请输入公式" />
					<!-- :disabled="action == 'edit'" -->
				</el-form-item>
				<div style="margin-bottom: 10px;">选择参数</div>
				<div style="padding: 20px;border: #DCDFE6 solid 1px;">

					<el-form-item label="年月" prop="year">
						<el-date-picker @change="selectChangedTime" v-model="userForm.year" type="month"
							placeholder="选择月">
						</el-date-picker>
					</el-form-item>

					<el-form-item label="计算参数" prop="id">
						<el-select v-model="userForm.ids" @change="selectChanged" placeholder="请选择用计算参数">
							<el-option :value="0" label=" "></el-option>
							<el-option v-for="role in userForm.List" :key="role.id" :label="role.type" :value="role.name">
							</el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="计算符号">
						<el-select v-model="userForm.symbol" @change="selectChangedSymbol">
							<el-option :value="0" label=" "></el-option>
							<el-option :value="1" label="+"></el-option>
							<el-option :value="2" label="-"></el-option>
						</el-select>
					</el-form-item>
				</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">取 消</el-button>
					<el-button @click="handleResetEx">重置</el-button>
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script>
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref,
		toRaw
	} from "vue";
	import utils from "../utils/utils";
	export default {
		name: "user",
		setup() {
			//   获取Composition API 上下文对象
			const {
				proxy
			} = getCurrentInstance();
			// 初始化用户表单对象
			const user = reactive({
				// state: 0,
			});
			// 初始化用户列表数据
			const userList = ref([]);
			// 初始化分页对象
			const pager = reactive({
				page: 1,
				pageSize: 10,
			});
			const symbol = ref("+");
			// 选中用户列表对象
			const checkedUserIds = ref([]);
			// 弹框显示对象
			const showModal = ref(false);
			// 新增用户Form对象
			const userForm = reactive({
				expression: '',
				expressionList: '',
        type:1,
        year:""
			});
			const salaryType = reactive({});
			const id = ref(0);
			const index = ref(0);
			// 所有角色列表
			const roleList = ref([]);
			// 所有部门列表
			const deptList = ref([]);
			// 定义用户操作行为
			const action = ref("add");
			// 定义表单校验规则
			const rules = reactive({
				name: [{
					required: true,
					message: "请输入公式名称",
					trigger: "blur",
				}, ],
				expression: [{
					required: true,
					message: "请输入公式",
					trigger: "blur",
				}, ],
        type: [{
          required: true,
          message: "请选择公式类型",
          trigger: "blur",
        }, ],
        year: [{
          required: true,
          message: "请选择年月",
          trigger: "blur",
        }, ]
			});
			// 定义动态表格-格式
			const columns = reactive([
        //   {
				// 	label: "公式ID",
				// 	prop: "id",
				// },
				{
					label: "公式名",
					prop: "name",
				},
				{
					label: "公式",
					prop: "expression",
				},
				// {
				// 	label: "公式1",
				// 	prop: "expressionList",
				// },
				{
					label: "类型",
					prop: "type",
					formatter(row, column, value) {
						return {
							1: "应发工资",
							2: "实发工资",
						} [value];
					},
				},
				// {
				//   label: "用户状态",
				//   prop: "state",
				//   formatter(row, column, value) {
				//     return {
				//       1: "在职",
				//       2: "离职",
				//       3: "试用期",
				//     }[value];
				//   },
				// },
				{
					label: "创建时间",
					prop: "createTime",
					width: 180,
					// formatter: (row, column, value) => {
					//   return utils.formateDate(new Date(value));
					// },
				},
				// {
				//   label: "最后登录时间",
				//   prop: "lastLoginTime",
				//   width: 180,
				//   formatter: (row, column, value) => {
				//     return utils.formateDate(new Date(value));
				//   },
				// },
			]);
			// 初始化接口调用
			onMounted(() => {
				getUserList();
				// getDeptList();
				/* getRoleAllList(); */
			});
			// 获取用户列表
			const getUserList = async () => {
				let params = {
					...user,
					...pager
				};
				try {
					const list = await proxy.$api.FindAll(params); //getUserList
					userList.value = list.rows;
					pager.total = list.records;
				} catch (error) {}
			};
			//  查询事件，获取用户列表
			const handleQuery = () => {
				getUserList();
			};
			// 重置查询表单
			const handleReset = (form) => {
				proxy.$refs[form].resetFields();
			};
			// 重置公式x
			const handleResetEx = (form) => {
				index.value = 0;
				userForm.year = "";
				userForm.List ="";
				userForm.ids ="";
				userForm.expressionList = "";
				userForm.expression = "";
			};
			// 分页事件处理
			const handleCurrentChange = (current) => {
				pager.page = current;
				getUserList();
			};
			// 用户单个删除
			const handleDel = async (row) => {
				let params = toRaw(row);
				await proxy.$api.Delete(params);
				proxy.$message.success("删除成功");
				getUserList();
			};
			// 批量删除
			const handlePatchDel = async () => {
				if (checkedUserIds.value.length == 0) {
					proxy.$message.error("请选择要删除的用户");
					return;
				}
				const res = await proxy.$api.userDel({
					userIds: checkedUserIds.value, //可单个删除，也可批量删除
				});
				if (res.nModified > 0) {
					proxy.$message.success("删除成功");
					getUserList();
				} else {
					proxy.$message.success("修改失败");
				}
			};

			// 表格多选
			const handleSelectionChange = (list) => {
				let arr = [];
				list.map((item) => {
					arr.push(item.userId);
				});
				checkedUserIds.value = arr;
			};
			// 用户新增
			const handleCreate = () => {
				action.value = "add";
				showModal.value = true;
			};

			// const getDeptList = async () => {
			//   let list = await proxy.$api.getDeptList();
			//   deptList.value = list;
			// };

			// // 角色列表查询
			// const getRoleAllList = async () => {
			//   let list = await proxy.$api.getRoleAllList();
			//   roleList.value = list;
			// };
			// 用户弹窗关闭
			const handleClose = () => {
				showModal.value = false;
				handleReset("dialogForm");
				index.value = 0;
				userForm.List ="";
				userForm.ids ="";
				userForm.year = "";
				handleResetEx();
			};
			// 用户提交
			const handleSubmit = () => {
				proxy.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						let params = toRaw(userForm);
						// if(params.name.indexOf("应发") == -1 || params.name.indexOf("实发") == -1){
						// 	proxy.$message.error("公式名称必须包含 '应发' 或 '实发' 字符");
						// 	return;
						// }
						let res = await proxy.$api.add(params);
						if (res == -5) {
							proxy.$message.error("公式名称重复");
							return;
						}
						showModal.value = false;
						proxy.$message.success("增加成功");
						handleReset("dialogForm");
						index.value = 0;
						userForm.List ="";
						userForm.ids ="";
						userForm.year = "";
						handleResetEx();
						getUserList();
					}
				});
			};
			// 用户编辑
			const handleEdit = (row) => {
				action.value = "edit";
				showModal.value = true;
				proxy.$nextTick(() => {
					Object.assign(userForm, row);
				});
			};

      const selectChangedType = (value) => {
        console.log(value);
        userForm.type = value;
      };
			const selectChanged = (value) => {
				//console.log(value);
				if (value == 0) {
					proxy.$message.error("请选择计算参数");
					return;
				}
				if (index.value % 2 != 0) {
					proxy.$message.error("请选择计算符号");
					userForm.ids = 0;
					return;
				}
				if(userForm.expressionList.indexOf(value) != -1){
					proxy.$message.error("该计算参数已选择，请重新选择");
					userForm.ids = 0;
					return;
				}
				for(var i =0; i < userForm.List.length; i++){
					var item = userForm.List[i];
					if(item.name == value){
						if (userForm.expressionList == "") {
							userForm.expression += item.type;
							userForm.expressionList = value + ',+';
						} else {
							userForm.expression += item.type;
							userForm.expressionList += ',' + value + symbol.value;
						}
					}
				}
				index.value += 1;
			};
			const selectChangedSymbol = (value) => {
				//console.log(value);
				if (value == 0) {
					proxy.$message.error("请选择计算符号");
					return;
				}
				if (index.value % 2 != 1) {
					userForm.symbol = 0;
					proxy.$message.error("请选择计算参数");
					return;
				}
				if (userForm.expression != "") {
					if (value == 1) {
						userForm.expression += "+";
						symbol.value = ",+";
					} else {
						userForm.expression += "-";
						symbol.value = ",-";
					}
				} else {
					proxy.$message.error("请选择计算参数");
					return;
				}
				index.value += 1;
				userForm.symbol = 0;
			};
			const selectChangedTime = async (val) => {
				if (val == null) {
					return;
				}
				const ye = val.getFullYear();
				const MO = val.getMonth() + 1;
        let yearMonth = "";
        if(MO < 10){
          yearMonth = ye+'-'+ '0' + MO;
        }else{
          yearMonth = ye+'-'+MO;
        }

        userForm.year = yearMonth;
				let params = {
          time: yearMonth
				};
				try {
					let list = await proxy.$api.FindList(params);
					userForm.List = list;
				} catch (error) {}
			};
			return {
				symbol,
				index,
				id,
				user,
				userList,
				columns,
				pager,
				checkedUserIds,
				showModal,
				userForm,
				salaryType,
				rules,
				roleList,
				deptList,
				action,
				getUserList,
				handleQuery,
				handleReset,
				handleResetEx,
				handleCurrentChange,
				handleDel,
				handlePatchDel,
				handleSelectionChange,
				handleCreate,
				// getRoleAllList,
				// getDeptList,
				handleClose,
				handleSubmit,
				handleEdit,
				selectChanged,
				selectChangedSymbol,
				selectChangedTime,
        selectChangedType
			};
		},
	};
</script>

<style lang="scss">
</style>
